package cn.it.shop.util;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import cn.it.shop.service.FileUploadUtil;

@Component("fileUploadUtil")
public class FileUploadUtilImpl implements FileUploadUtil {
	
	@Value(value="#{public.basePath}" + "#{public.image}")
	private String filePath="C:\\";
	
//	@Value(value="#{public.basePath}" + "#{public.image}")
//	public void setFilePath(String filePath) {
//		System.out.println("-------------->" + filePath);
//		this.filePath = filePath;
//	}

	// 获取后缀名
	private String getExt(String oldName){
		return FilenameUtils.getExtension(oldName);
	}
	
	// 2: UUID生成随机名称(新文件名)
	private String newName(String oldName){
		// 获取后缀名
		String ext=this.getExt(oldName);
		return UUID.randomUUID().toString() + "." + ext;
	}
	
	

	@Override// 3: 实现文件上传功能, 传入,要上传的文件, 和目标路径即可
	public String uploadFile(File file, String oldName) {
		String newName=this.newName(oldName);
		try {
			FileUtils.copyFile(file,new File(filePath,newName));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}finally{
			file.delete();
		}
		return newName;
	}
}
